<template>
  <div class="ct-collapse"><slot /></div>
</template>
<script setup>
import { ref, provide } from 'vue'
import propsOptions, { collapsecontextKey } from './props.js'
defineOptions({
  name: 'CTCollapse',
})
const props = defineProps(propsOptions)
const activeName = ref(props.modelValue)
const emit = defineEmits(['update:modelValue', 'change'])

const handlerItemClick = (currentItemName) => {
  let _activeNameArr = [...activeName.value]
  if (props.accordion) {
    // 手风琴模式 只打开一个
    _activeNameArr = [activeName.value[0] === currentItemName ? '' : currentItemName]
  } else {
    // 普通模式 不进行自动折叠
    if (_activeNameArr.includes(currentItemName)) {
      _activeNameArr = _activeNameArr.filter((item) => item !== currentItemName)
    } else {
      _activeNameArr.push(currentItemName)
    }
  }
  activeName.value = _activeNameArr
  emit('update:modelValue', _activeNameArr)
  emit('change', _activeNameArr)
}

provide(collapsecontextKey, {
  activeName,
  handlerItemClick,
})
</script>
<style lang="scss" scoped></style>
